<style lang="less">
.comment-manage {
  .comment-manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0px;
  }

  .comment-manage-title {
    margin: 0;
    color: #303133;
  }

  .comment-manage-footer {
    margin-top: 15px;
    text-align: right;
  }

  .date-time {
    line-height: 1.5;
    white-space: pre-line;
  }

  .search-box {
    margin: 0;
  }

  .content-cell {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
<template>
  <div class="comment-manage">
    <div class="comment-manage-header">
      <h3 class="comment-manage-title">评论管理</h3>
      <div class="search-box">
        <el-input v-model="search" size="small" placeholder="输入关键字搜索（内容、文章标题或用户名）" clearable @clear="handleSearchClear"
          @keyup.enter.native="handleSearch" style="width: 350px;">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>
    <div class="comment-manage-wrap">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="id" width="80" align="center"></el-table-column>
        <el-table-column label="内容" prop="content" show-overflow-tooltip class-name="content-cell"></el-table-column>
        <el-table-column label="来源文章" prop="article_title" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="发布账号" prop="username" width="120"></el-table-column>
        <el-table-column label="发布时间" width="150">
          <template slot-scope="scope">
            <div class="date-time">{{ formatDateTime(scope.row.createAt) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 'published' ? 'success' : scope.row.status === 'hidden' ? 'warning' : 'info'"
              size="small">
              {{ scope.row.status === 'published' ? '已发布' : scope.row.status === 'hidden' ? '已隐藏' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 'published'" size="mini" type="warning" @click="handleHide(scope.$index, scope.row)">隐藏</el-button>
            <el-button v-if="scope.row.status === 'hidden'" size="mini" type="success" @click="handleRestore(scope.$index, scope.row)">显示</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="comment-manage-footer">
      <el-pagination @current-change="currentChangeFn" background layout="prev, pager, next" :page-size="page_size"
        :pager-count="7" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { itemsComment, deleteComment, searchComment, hideComment, restoreComment } from "../../api/index"
import { requireLogin } from "../../utils/auth"

export default {
  data() {
    return {
      tableData: [],
      search: '',
      page_num: 1,
      page_size: 10,
      total: 0,
      isAdmin: false
    }
  },
  created() {
    // 检查是否为管理员
    const role = localStorage.getItem("USER_ROLE")
    this.isAdmin = role === '1'
    
    // 如果不是管理员，跳转到首页
    if (!this.isAdmin) {
      this.$message.warning('您没有权限访问评论管理页面')
      this.$router.push({ path: "/home" }).catch(() => {})
      return
    }
    
    this.itemsCommentFn()
    this.$store.commit("addTab", this.$route)
  },
  methods: {
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day}\n${hours}:${minutes}:${seconds}`
    },
    // 隐藏评论
    async handleHide(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '您确定要隐藏这条评论吗？', '确定', '取消')
      if (result.isConfirmed) {
        this.hideCommentFn(row.id)
      }
    },
    // 恢复评论
    async handleRestore(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '您确定要恢复这条评论吗？', '确定', '取消')
      if (result.isConfirmed) {
        this.restoreCommentFn(row.id)
      }
    },
    // 删除评论
    async handleDelete(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '您确定要删除这条评论吗？', '确定', '取消')
      if (result.isConfirmed) {
        this.deleteCommentFn(row.id)
      }
    },
    // 分页变化处理
    currentChangeFn(index) {
      this.page_num = index
      // 如果有搜索关键词，执行搜索，否则加载列表
      if (this.search && this.search.trim()) {
        this.searchCommentFn()
      } else {
        this.itemsCommentFn()
      }
    },
    // 获取评论列表
    async itemsCommentFn() {
      let page_num = this.page_num
      let page_size = this.page_size
      await itemsComment({ page_num, page_size })
        .then(resData => {
          if (resData.code == 200) {
            this.tableData = resData.data || []
            this.total = resData.total || 0
          } else {
            this.tableData = []
            this.total = 0
          }
        })
        .catch(err => {
          console.error('获取评论列表失败:', err)
          this.tableData = []
          this.total = 0
        })
    },
    // 搜索评论
    async searchCommentFn() {
      const keyword = this.search ? this.search.trim() : ''
      if (!keyword) {
        // 如果关键词为空，加载普通列表
        this.itemsCommentFn()
        return
      }

      await searchComment({ keyword })
        .then(resData => {
          if (resData.code == 200 && resData.data) {
            const searchResults = Array.isArray(resData.data) ? resData.data : []
            this.tableData = searchResults
            this.total = searchResults.length
          } else {
            this.tableData = []
            this.total = 0
          }
        })
        .catch(err => {
          console.error('搜索评论失败:', err)
          this.tableData = []
          this.total = 0
          this.$showError && this.$showError('搜索失败', '搜索评论时发生错误，请重试')
        })
    },
    // 隐藏评论
    async hideCommentFn(id) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      await hideComment({ id })
        .then(resData => {
          if (resData.code == 200) {
            this.$showSuccess('成功', resData.msg || '隐藏成功')
            this.itemsCommentFn()
          } else {
            this.$showError('失败', resData.msg || '隐藏失败')
          }
        })
        .catch(() => {
          this.$showError('失败', '隐藏失败，请重试')
        })
    },
    // 恢复评论
    async restoreCommentFn(id) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      await restoreComment({ id })
        .then(resData => {
          if (resData.code == 200) {
            this.$showSuccess('成功', resData.msg || '恢复成功')
            this.itemsCommentFn()
          } else {
            this.$showError('失败', resData.msg || '恢复失败')
          }
        })
        .catch(() => {
          this.$showError('失败', '恢复失败，请重试')
        })
    },
    // 删除评论
    async deleteCommentFn(id) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      await deleteComment({ id })
        .then(resData => {
          if (resData.code == 200) {
            this.$showSuccess('成功', resData.msg || '删除成功')
            this.itemsCommentFn()
          } else {
            this.$showError('失败', resData.msg || '删除失败')
          }
        })
        .catch(() => {
          this.$showError('失败', '删除失败，请重试')
        })
    },
    // 搜索处理
    handleSearch() {
      this.page_num = 1
      const keyword = this.search ? this.search.trim() : ''
      if (keyword) {
        this.searchCommentFn()
      } else {
        this.itemsCommentFn()
      }
    },
    // 清空搜索
    handleSearchClear() {
      this.search = ''
      this.page_num = 1
      this.itemsCommentFn()
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  }
}
</script>

